<template>
  <div>
    远程组件正在加载中，当你看到这个组件
    <component :is="mode" v-bind="$attrs"></component>
  </div>
</template>

<script>
/**
 * 远程加载基础组件
 *
 */
import {
  markRaw,
  h,
  onMounted,
  ref,
  reactive,
  defineComponent,
  watch
} from 'vue'
export default defineComponent({
  name: 'RemoteBaseComponent',
  inheritAttrs: false,
  props: {
    componentInfo: {
      type: Object,
      default() {
        return {
          js: '',
          css: '',
          componentName: '',
        }
      }
    }
  },
  setup(props, { emit }) {
    let mode = ref(null)
    console.log(props.componentInfo)
    const componentInfo = reactive(props.componentInfo)
    /**
     * 使用动态 script方式加载远程js
     */
    function asyncScript(url) {
      // 动态script
      return new Promise((resolve, reject) => {
        const script = document.createElement('script')
        const target =
          document.getElementsByTagName('script')[0] || document.head
        script.type = 'text/javascript'
        script.src = url
        script.onload = resolve
        script.onerror = reject
        target.parentNode.insertBefore(script, target)
      })
    }
    async function loadScript(url, componentName) {
      // 动态script
      await asyncScript(url)
      console.log(window[componentName])
      mode.value = markRaw(window[componentName].default[componentName])
    }

    function loadStyles(url) {
      let link = document.createElement('link')
      link.rel = 'stylesheet'
      link.type = 'text/css'
      link.href = url
      let head = document.getElementsByTagName('head')[0]
      head.appendChild(link)
    }
    onMounted(async () => {
      console.log('执行了远程加载组件代码吗？')
      loadStyles(componentInfo.css)
      loadScript(componentInfo.js,componentInfo.componentName, componentInfo.componentName)
    })
    return {
      mode
    }
  }
})
</script>